/*
 * Copyright (c) 2010, Jan Pastor. All Rights Reserved.
 */

package sk.jp.jitag.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sk.jp.commons.exception.IllegalInputException;
import sk.jp.commons.ui.ExceptionDialog;
import sk.jp.commons.ui.InfoDialog;
import sk.jp.commons.ui.LeaveGridLayout;
import sk.jp.commons.ui.WarningDialog;
import sk.jp.commons.ui.TextDialog;
import sk.jp.commons.utils.ExceptionUtils;
import sk.jp.commons.utils.LogMsg;
import sk.jp.commons.utils.StringUtils;
import sk.jp.jitag.model.config.Tool;
import sk.jp.jitag.util.Msg;

public class ToolDialog extends JDialog implements ActionListener {

    private static final Logger log = LoggerFactory.getLogger(ToolDialog.class);

    private enum ActionCode {
        save,
        cancel,
        help,
        ;
    }

    private JTextField label;
    private JTextField cmdline;

    private Tool toolToEdit = null;
    private Tool tool = null;

    //----------------------------------------------------------------------

    public ToolDialog(JDialog ownerDialog) throws HeadlessException {
        super(ownerDialog, Msg.toolDialogTitleNew.value(), true); //New tool
    }

    public ToolDialog(JDialog ownerDialog, Tool toolToEdit) throws HeadlessException {
        super(ownerDialog, Msg.toolDialogTitleEdit.value(), true); //Edit tool properties

        this.toolToEdit = toolToEdit;
    }

    //----------------------------------------------------------------------

    public void open(){
        init();

        pack();
        label.requestFocusInWindow();

        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenDimension = toolkit.getScreenSize();
        Dimension size = getSize();
        setLocation((screenDimension.width - size.width) / 2,
                    (screenDimension.height - size.height) / 2);

        setVisible(true);
    }

    /**
     * @return created tool instance or null if dialog was cancelled.
     */
    public Tool getTool(){
        log.trace(LogMsg.out("tool", tool));
        return tool;
    }

    //----------------------------------------------------------------------

    @Override
    public void setVisible(boolean visible) {
        if(!visible){
            //on close
            actionCancel();
        }
        super.setVisible(visible);
    }

    private void init(){
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        LeaveGridLayout leaveGridLayout;
        leaveGridLayout = new LeaveGridLayout(2, 2, 4, 5,
                                                LeaveGridLayout.HAlign.left,
                                                LeaveGridLayout.VAlign.top);
        leaveGridLayout.setColumnsHAlign(LeaveGridLayout.HAlign.right, LeaveGridLayout.HAlign.left);
        JPanel mainPanel = new JPanel(leaveGridLayout);
        contentPane.add(mainPanel, BorderLayout.CENTER);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(6, 4, 6, 4));

        mainPanel.add(new JLabel(Msg.toolDialogLabel.value()));//Label:
        label = new JTextField(25);
        mainPanel.add(label);

        mainPanel.add(new JLabel(Msg.toolDialogCmdline.value()));//Command line:
        cmdline = new JTextField(25);
        mainPanel.add(cmdline);

        //Buttons
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        contentPane.add(buttonPanel, BorderLayout.PAGE_END);
        //
        buttonPanel.add(createButton(Msg.commonOk, ActionCode.save)); //OK
        buttonPanel.add(createButton(Msg.commonCancel, ActionCode.cancel));  //Cancel
        buttonPanel.add(createButton(Msg.commonHelp, ActionCode.help));  //Help

        if(toolToEdit != null){
            label.setText(toolToEdit.getLabel());
            cmdline.setText(toolToEdit.getCmdLine());
        }
    }

    private JButton createButton(Msg btnLabel, ActionCode actionCode){
        JButton button = new JButton(btnLabel.value());
        button.setActionCommand(actionCode.name());
        button.addActionListener(this);
        return button;
    }

    public void actionPerformed(ActionEvent event) {
        try {
            processAction(ActionCode.valueOf(event.getActionCommand()));
        }catch(IllegalInputException e){
            new WarningDialog().show(this, ExceptionUtils.translateException(e));
        }catch(Exception e){
            ExceptionDialog.show(this, e);
        }
    }

    private void processAction(ActionCode actionCode){
        log.trace(LogMsg.inp("actionCode", actionCode));
        if(actionCode == ActionCode.cancel){
            actionCancel();
        }else if(actionCode == ActionCode.save){
            actionSave();
        }else if(actionCode == ActionCode.help){
            actionHelp();
        }else{
            new InfoDialog().show(this, "Not yet implemented");
        }
    }

    private void actionCancel(){
        tool = null;
        dispose();
    }

    private void actionSave(){
        String labelText = label.getText();
        String cmdlineText = cmdline.getText();
        if(StringUtils.isNullOrEmpty(labelText)){
            throw new IllegalInputException("Missing required value",
                                            Msg.toolDialogMisReq.getPropKey(),
                        ExceptionUtils.paramsToMap("field", Msg.toolDialogLabel.value()));
        }
        if(StringUtils.isNullOrEmpty(cmdlineText)){
            throw new IllegalInputException("Missing required value",
                                            Msg.toolDialogMisReq.getPropKey(),
                        ExceptionUtils.paramsToMap("field", Msg.toolDialogCmdline.value()));
        }

        tool = new Tool(labelText, cmdlineText);
        //
        dispose();
    }

    private void actionHelp(){
        TextDialog td = new TextDialog(this, Msg.toolDialogHelpTitle.value(), true);
        td.setBgColor(Color.WHITE);
        td.open("<body style=\"font-family: sans-serif;\">" + Msg.toolDialogHelp.value() + "</body>");
    }

}